<?php

namespace app\app\controller;

use app\app\model\ProjectLZModel;
use app\app\model\ProjectModel;
use app\app\model\ProjectViolationModel;
use app\app\model\ProjectZrrDetailModel;
use app\app\model\RandModel;
use app\app\model\SysDictDataModel;
use app\app\model\SysFileInfoModel;
use app\BaseController;
use app\app\model\ProjectCheckModel;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;


class ProjectCheck extends BaseController
{
    public function index()
    {
        $project_id = input('project_id', '');
        $page_size = input('pageSize', '20');
        $state = input('state', '1');
        $type = input('check_source', '');
        $user_name = input('user_name', '');


        $where[] = ['a.project_id', '=', $project_id];
        $where[] = ['a.state', '=', $state];
        if ($user_name) $where[] = ['a.check_user', '=', $user_name];
        if ($type) $where[] = ['a.check_source', '=', $type];
        $list = ProjectCheckModel::alias('a')
            ->field('a.*,b.peccancy_type,b.peccancy_content')
            ->leftjoin('t_project_peccancy b', 'a.peccancy_id = b.id')
            ->where($where)->paginate($page_size);
        $this->success('success', $list);
    }

//    public function checkList()
//    {
//        $project_id = input('project_id');
//        $type = input('type_name', '');
//        $where[] = ['a.project_id', '=', $project_id];
//        if ($type) $where[] = ['a.check_source', '=', $type];
//        $list = ProjectCheckModel::alias('a')
//            ->field('a.*,b.peccancy_type,b.peccancy_content')
//            ->leftjoin('t_project_peccancy b', 'a.peccancy_id = b.id')
//            ->where($where)->select();
//        $this->success('success', $list);
//    }


    /**
     * 违章分类列表
     */

    public function violation()
    {
        $page_size = input('pageSize', '20');
        $name = input('peccancy_content', '');
        $peccancy_level = input('lvl', '');
        $type = input('type', '');
        $peccancy_type = input('peccancy_type', '');
        $where = '1=1';
        if ($type) $where .= " AND type LIKE '%" . $type . "%'";
        if ($peccancy_type) $where .= " AND peccancy_type LIKE '%" . $peccancy_type . "%'";
        if ($name) $where .= " AND peccancy_content LIKE '%" . $name . "%'";
        if ($peccancy_level) $where .= " AND peccancy_level ='" . $peccancy_level . "'";
        $list = ProjectViolationModel::where($where)->paginate($page_size);
        $this->success('success', $list);
    }


    /**
     * 输变电下安全问题汇总列表
     */
    public function list()
    {
        $data = $this->request->param();
        $page_size = input('pageSize', '20');
        $check_type = input('check_type', '2');
        $state = input('state', '1');
        $where[] = ['c.state', '=', 2];
        //项目名查询
        if (isset($data['project_name'])) {
            $where[] = ['b.project_name|a.project_name', 'like', '%' . $data['project_name'] . '%'];
        }

        $total = ProjectCheckModel::count();
        $unchanged_total = ProjectCheckModel::where('zg_flag', 0)->count();

        $one_total = ProjectCheckModel::where('issue_level', 'Ⅰ')->count();
        $two_total = ProjectCheckModel::where('issue_level', 'Ⅱ')->count();
        $three_total = ProjectCheckModel::where('issue_level', 'Ⅲ')->count();
        $fk_money = ProjectCheckModel::sum('fk_money');
        $data = array(
            'total' => $total,
            'unchanged_total' => $unchanged_total,
            'one_total' => $one_total,
            'two_total' => $two_total,
            'three_total' => $three_total,
            'fk_money' => round($fk_money / 10000, 2),
        );

        if ($state == 2) {
            $where[] = ['c.zg_flag', '=', 0];
        } elseif ($state == 3) {
            $where[] = ['c.fk_money', '>', 0];
        } elseif ($state == 4) {
            $where[] = ['c.issue_level', '=', 'Ⅰ'];
        } elseif ($state == 5) {
            $where[] = ['c.issue_level', '=', 'Ⅱ'];
        } elseif ($state == 6) {
            $where[] = ['c.issue_level', '=', 'Ⅲ'];
        } else {
        }
        $list = ProjectModel::alias('a')
            ->field('a.*,b.project_name as project_main_name,b.id as main_id,b.kg_time as kg_main_time,b.tc_time as tc_main_time')
            ->join('t_project b', 'a.link_project_id = b.id')
            ->join('t_project_check c', 'a.id = c.project_id')
            ->group('a.project_name')
            ->where($where)
            ->order('a.project_dy_level desc')->paginate($page_size)->toArray();
        $info = $list['data'];

        $tmp_arr = array();
        $temp = array();
        foreach ($info as $k => $v) {
            if (!in_array($v['main_id'], $tmp_arr)) {
                $tmp_arr[$k] = $v['main_id'];
                $temp[$k]['id'] = $v['main_id'];
                $temp[$k]['project_name'] = $v['project_main_name'];
                $temp[$k]['kg_time'] = $v['kg_main_time'];
                $temp[$k]['kg_time'] = $v['tc_main_time'];
            }
        }
        foreach ($temp as $key => $value) {
            foreach ($info as $k => $v) {
                if ($value['id'] == $v['link_project_id']) {
                    $temp[$key]['children'][] = $v;
                }
            }
            $list['data'] = $temp;
        }

        $res = array(
            'tongJi' => $data,
            'list' => $list,

        );

        $this->success('success', $res);
    }


    /**
     * 巡查问题详情  (已废弃)
     */
    public function info()
    {
        $id = input('id', '');
        $list = ProjectCheckModel::alias('a')
            ->field('a.*,b.file_name as check_name,b.file_path as check_path,c.file_name,c.file_path,d.peccancy_content')
            ->leftjoin('sys_file_info b', 'b.file_id = a.check_photo_id')
            ->leftjoin('sys_file_info c', 'b.file_id = a.check_file_id')
            ->leftjoin('t_project_peccancy d', 'd.id = a.peccancy_id')
            ->where('a.project_id', $id)->find();
        $this->success('success', $list);
    }


    /** 问题统计
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function problem()
    {
        $project_id = input('project_id');
        $total = ProjectCheckModel::where('project_id', $project_id)
            ->where('zg_flag', 0)->count();
        $unchanged_total = ProjectCheckModel::where('project_id', $project_id)
            ->where('zg_flag', 0)->count();

        $one_total = ProjectCheckModel::where('project_id', $project_id)
            ->where('issue_level', 'Ⅰ')->count();
        $two_total = ProjectCheckModel::where('project_id', $project_id)
            ->where('issue_level', 'Ⅱ')->count();
        $three_total = ProjectCheckModel::where('project_id', $project_id)
            ->where('issue_level', 'Ⅲ')->count();
        $data = array(
            'total' => $total,
            'unchanged_total' => $unchanged_total,
            'one_total' => $one_total,
            'two_total' => $two_total,
            'three_total' => $three_total,
            'three_total' => $three_total
        );

        $list = SysDictDataModel::where('dict_type', 'check_source')->select();
        $res = array(
            'tongJi' => $data,
            'list' => $list,

        );
        $this->success('success', $res);
    }


    /**  巡查问题添加（待提交状态）
     * @param Request $request
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function add(Request $request)
    {
        $data = $request->param();
        $data['id'] = RandModel::randId();
        $data['check_time'] = date('Y-m-d H:i:s', time());

        if (isset($data['peccancy_id']) && !empty($data['peccancy_id'])) {
            $violation = ProjectViolationModel::where('id', $data['peccancy_id'])->find();
            $data['issue_level'] = $violation['peccancy_level'];
        }

        $start_time = date('Y-m-d 00:00:00', time());
        $end_time = date('Y-m-d  23:59:59', time());
        $where[] = ['lz_time', 'BETWEEN', [$start_time, $end_time]];
        $where[] = ['user_name', '=', $data['check_user']];
        $info = ProjectLZModel::where($where)->find();
        if (isset($info['id'])) $data['project_lz_id'] = $info['id'];

        ProjectCheckModel::create($data);
        $this->success('提交成功');
    }


    /**
     * 批量修改状态（提交以及软删除）
     */
    public function refer()
    {
        $ids = input('ids');
        $id_arr = explode(',', $ids);
        $data['state'] = input('state');
        ProjectCheckModel::where('id', 'in', $id_arr)->update($data);

        //如果提交需扣除责任人分数
        if ($data['state'] == 2) {
            $list = ProjectCheckModel::where('id', 'in', $id_arr)->select();
            $ProjectZrrCommentModel = new \app\app\model\ProjectZrrCommentModel;
            $todo_task_list = array();
            foreach ($list as $key => $value) {
                if ($value['zrr_id']) {
                    $zzr = ProjectZrrDetailModel::where('id', 'in', $value['zrr_id'])->select();
                    if ($zzr) {
                        foreach ($zzr as $k => $v) {
                            $save['score'] = floatval($v['score']) - floatval(1);
                            $info = ProjectZrrDetailModel::where('id', $v['id'])->update($save);
                            $item['detail_id'] = $v['id'];
                            $item['score'] = 1;
                            $item['content'] = $value['check_content'];
                            $item['pic_id'] = $value['check_file_id'];
                            $item['create_time'] = date('Y-m-d H:i:s', time());
                            array_push($todo_task_list, $item);
                        }
                    }
                }
            }
            if (count($todo_task_list)) {
                $ProjectZrrCommentModel->saveAll($todo_task_list, false);
            }
        }
        $this->success('success');
    }

    /**
     * 查询项目列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function listGroup()
    {
        $name = input('name/s', '');

        $start_time = date('Y-01-01 00:00:00', time());
        $end_time = date('Y-12-31 23:59:59', time());
        $where[] = ['b.tc_time', '>=', $start_time];
        $where[] = ['b.kg_time', '<=', $end_time];
        if ($name) {
            $where[] = ['b.project_name|c.project_name', 'like', '%' . $name . '%'];
        }
        $data = ProjectCheckModel::alias('a')
            ->leftJoin('t_project b', 'a.project_id = b.id')
            ->leftJoin('t_project c', 'b.link_project_id = c.id')
            ->where($where)
            ->group('b.id')
            ->field('b.id,b.link_project_id,b.is_parent')
            ->select();

        $project_id_array = array_column($data->toArray(), null, 'id');
        $project_id_array = array_keys($project_id_array);

        $result = [];
        foreach ($data as $v) {
            if ($v['is_parent'] == 0) {
                $result[$v['id']] = $v;
                continue;
            }

            $result[$v['link_project_id']]['children'][$v['id']]['children'][] = $v;
        }

        $project_id_array = array_merge($project_id_array, array_keys($result));

        $project = ProjectModel::where('id', 'in', $project_id_array)
            ->field('id, project_name')
            ->select();
        $project = array_column($project->toArray(), null, 'id');

        $result = $this->getProject($result, $project);

        $this->success('success', $result);
    }

    /**
     * 整理项目组列表
     * @param $data
     * @param $project
     * @return array
     */
    public function getProject($data, $project)
    {
        foreach ($data as $k => &$v) {
            $tmp = $v['children'];
            if (isset($project[$k])) {
                $v = $project[$k];
                $v['children'] = $this->getProject($tmp ?: [], $project);

                if (isset($v['children'][0]['link_project_id'])) {
                    unset($v['children']);
                }
            }
        }

        return array_values($data);
    }

    /**
     * 查询指定项目id下的检查列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function checkList()
    {
        $page_size = input('pageSize', '20');

        $where = $this->request->param();
        unset($where['page'], $where['pageSize']);
        $where = array_filter($where);
        empty($where['project_id']) && $this->error('请传入project_id');

//        $tmp = [];
//        foreach ($where as $k => $v) {
//            $tmp['a.' . $k] = $v;
//        }
//        $where = $tmp;
//        unset($tmp);

        $data = ProjectCheckModel::where($where)->paginate($page_size);

        empty($data) && $this->error('未找到符合条件的资源');
        $data = $data->toArray();
        empty($data['data']) && $this->error('未找到符合条件的数据');

        $this->success('success', $data);
    }

    /**
     * 风险详情接口
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function detail()
    {
        $id = input('id/s');
        if (!$id) $this->error('请传入id');

        $check = ProjectCheckModel::where('id', $id)
            ->find();

        if (empty($check)) $this->error('未找到符合条件的风险');

        $this->success('success', $check);
    }
}
